package com.czl.base.push;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.czl.base.R;
import com.czl.base.config.AppConstants;
import com.czl.base.event.LiveBusCenter;
import com.czl.base.util.MessageHelper;
import com.czl.base.util.SpHelper;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.api.UPushRegisterCallback;
import com.umeng.message.entity.UMessage;

import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.android.agoo.xiaomi.MiPushRegistar;

/**
 * PushSDK集成帮助类
 */
public class PushHelper {

    private static final String TAG = "PushHelper";

    /**
     * 预初始化
     */
    public static void preInit(Context context) {
        //解决厂商通知点击时乱码等问题
        PushAgent.setup(context, PushConstants.APP_KEY, PushConstants.MESSAGE_SECRET);
        UMConfigure.preInit(context, PushConstants.APP_KEY, PushConstants.CHANNEL);
    }

    /**
     * 初始化
     */
    public static void init(final Context context) {
        // 基础组件包提供的初始化函数，应用配置信息：http://message.umeng.com/list/apps
        // 参数一：上下文context；
        // 参数二：应用申请的Appkey；
        // 参数三：发布渠道名称；
        // 参数四：设备类型，UMConfigure.DEVICE_TYPE_PHONE：手机；UMConfigure.DEVICE_TYPE_BOX：盒子；默认为手机
        // 参数五：Push推送业务的secret，填写Umeng Message Secret对应信息
        UMConfigure.init(context, PushConstants.APP_KEY, PushConstants.CHANNEL,
                UMConfigure.DEVICE_TYPE_PHONE, PushConstants.MESSAGE_SECRET);

        //获取推送实例
        PushAgent pushAgent = PushAgent.getInstance(context);

        //TODO:需修改为您app/src/main/AndroidManifest.xml中package值
        pushAgent.setResourcePackageName("com.czl.base");
        //如果您的应用在前台，您可以设置不显示通知消息
        pushAgent.setNotificationOnForeground(true);
        //推送设置
        pushSetting(context);
        //注册推送服务，每次调用register方法都会回调该接口
        pushAgent.register(new UPushRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.i(TAG, "deviceToken --> " + deviceToken);
                SpHelper.INSTANCE.encode(AppConstants.SpKey.DEVICE_TOKEN, deviceToken);
            }

            @Override
            public void onFailure(String errCode, String errDesc) {
                SpHelper.INSTANCE.encode(AppConstants.SpKey.DEVICE_TOKEN, "");
                Log.e(TAG, "register failure：--> " + "code:" + errCode + ",desc:" + errDesc);
            }
        });
        registerDeviceChannel(context);
    }

    /**
     * 注册设备推送通道（小米、华为等设备的推送）
     */
    private static void registerDeviceChannel(Context context) {
        //小米通道，填写您在小米后台APP对应的xiaomi id和key
        MiPushRegistar.register(context, PushConstants.MI_ID, PushConstants.MI_KEY);
        //华为，注意华为通道的初始化参数在minifest中配置
        HuaWeiRegister.register((Application) context.getApplicationContext());
        //魅族，填写您在魅族后台APP对应的app id和key
//        MeizuRegister.register(context, PushConstants.MEI_ZU_ID, PushConstants.MEI_ZU_KEY);
        //OPPO，填写您在OPPO后台APP对应的app key和secret
        OppoRegister.register(context, PushConstants.OPPO_KEY, PushConstants.OPPO_SECRET);
        //vivo，注意vivo通道的初始化参数在minifest中配置
        VivoRegister.register(context);
    }

    //推送设置
    private static void pushSetting(Context context) {
        PushAgent pushAgent = PushAgent.getInstance(context);
        //设置通知栏显示通知的最大个数（0～10），0：不限制个数
        pushAgent.setDisplayNotificationNumber(1);

        //推送消息处理
        UmengMessageHandler msgHandler = new UmengMessageHandler() {
            //处理通知栏消息
            @Override
            public void dealWithNotificationMessage(Context context, UMessage msg) {
                super.dealWithNotificationMessage(context, msg);
                LogUtils.eTag(TAG, "notification receiver:" + msg.getRaw().toString());
            }

            //处理透传消息
            @Override
            public void dealWithCustomMessage(Context context, UMessage msg) {
                super.dealWithCustomMessage(context, msg);
                LogUtils.eTag(TAG, "custom receiver:" + msg.getRaw().toString());
            }

            @Override
            public Uri getSound(Context context, UMessage uMessage) {
                return getCustomSound(context, uMessage);
//                return super.getSound(context,uMessage);
            }

            //自定义通知样式，此方法可以修改通知样式等
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                if (msg.builder_id == 1) {
                    long curTime = System.currentTimeMillis();
                    int CHANNEL_ID = 101;
                    String newChannel = AppUtils.getAppName();
                    String CHANNEL_NAME = AppUtils.getAppName();
                    Uri sound = getSound(context, msg);

                    Intent hangIntent = new Intent(context, NotificationClickReceiver.class);
                    hangIntent.setAction(NotificationClickReceiver.DOWN_ACTION);
                    PendingIntent hangPendingIntent = PendingIntent.getBroadcast(context, (int) (curTime / 1000), hangIntent, PendingIntent.FLAG_ONE_SHOT);
                    long[] vibrate = new long[]{0, 500, 1000, 1500};
//                    Utils.Consumer<NotificationCompat.Builder> consumer = builder -> builder.setContentTitle(msg.title)
//                            .setContentText(msg.text)
//                            .setSmallIcon(R.mipmap.ic_clogo)
////                            .setContentIntent(hangPendingIntent)
//                            .setFullScreenIntent(hangPendingIntent, true)
//                            .setVibrate(vibrate)
//                            .setSound(sound)
//                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_clogo))
//                            .setAutoCancel(true);
//                    NotificationUtils.notify(CHANNEL_ID,consumer);
                    Notification notification = new NotificationCompat.Builder(context, newChannel)
                            .setContentTitle(msg.title)
                            .setContentText(msg.text)
                            .setSmallIcon(R.mipmap.ic_clogo)
//                            .setContentIntent(hangPendingIntent)
                            .setFullScreenIntent(hangPendingIntent, true)
                            .setVibrate(vibrate)
                            .setSound(sound)
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_clogo))
                            .setAutoCancel(true)
                            .build();

                    //Android 5.0 以上锁屏通知
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        notification.visibility = Notification.VISIBILITY_PUBLIC;
                    }

                    //Android 8.0 以上需包添加渠道
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

                        NotificationChannel notificationChannel = new NotificationChannel(newChannel, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                        //只能在create一个渠道之前修改铃声，在创建之后不支持修改
                        notificationChannel.setSound(sound, Notification.AUDIO_ATTRIBUTES_DEFAULT);
                        // 设置通知出现时的闪灯（如果 android 设备支持的话）
                        notificationChannel.enableLights(true);
                        notificationChannel.setLightColor(Color.RED);
                        // 设置通知出现时的震动（如果 android 设备支持的话）
                        notificationChannel.enableVibration(true);
                        notificationChannel.setVibrationPattern(vibrate);

                        manager.createNotificationChannel(notificationChannel);
                    }
                    LogUtils.eTag("umeng", "notificationDefault: " + getNotificationDefaults(context, msg));
                    return notification;
                }
                return super.getNotification(context, msg);
            }
        };

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            pushAgent.setMessageHandler(msgHandler);
        }

        //推送消息点击处理
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void openActivity(Context context, UMessage msg) {
                super.openActivity(context, msg);
                Log.i(TAG, "click openActivity: " + msg.getRaw().toString());
            }

            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);
                Log.i(TAG, "click launchApp: " + msg.getRaw().toString());
                LiveBusCenter.INSTANCE.postOpenPushMessageEvent(msg.getRaw().toString());
            }

            @Override
            public void dismissNotification(Context context, UMessage msg) {
                super.dismissNotification(context, msg);
                Log.i(TAG, "click dismissNotification: " + msg.getRaw().toString());
            }
        };
        pushAgent.setNotificationClickHandler(notificationClickHandler);
    }

    /**
     * 自定义通知声音
     *
     * @param context
     * @param uMessage
     * @return
     */
    private static Uri getCustomSound(Context context, UMessage uMessage) {
//        String soundPath = uMessage.sound;
        String soundPath = "android.resource://" + context.getPackageName() + "/raw/pushmusic";
        LogUtils.eTag("getCustomSound", "soundPath:" + soundPath);
        return Uri.parse(soundPath);
    }

}
